package com.huida.app.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huida.app.entity.AjaxResponse;
import com.huida.app.enums.CustomExceptionType;
import com.huida.app.exception.CustomException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 自定义登录失败的结果处理
 * @Author: Wangzz
 * @Version: 1.0.0
 * @CreateDate: Created in 2021/10/31 22:29
 * @UpdateDate: [dateFormat:YYYY-MM-DD][modifier][description]
 */

@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Value("${spring.security.logintype}")
    private String loginType;

    private static ObjectMapper objectMapper = new ObjectMapper();

    /*
    *   在上面的自定义登陆失败处理中，既适应JSON前后端分离的应用登录失败结果处理，也适用于模板页面跳转应用的登录失败结果处理
    *   登陆失败之后，将默认跳转到默认的failureUrl，即登录界面。
    * */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        if(loginType.equalsIgnoreCase("JSON")){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(
                    objectMapper.writeValueAsString(
                            AjaxResponse.error(
                                new CustomException(
                                        CustomExceptionType.USER_INPUT_ERROR,
                                        "用户名或密码存在错误，请检查后再次登录"
                                )
                            )
                    )
            );

        }else{
            response.setContentType("text/html;charset=UTF-8");
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
